package com.example.ql.express.utils;

import com.example.ql.express.model.constants.SystemCharConstant;
import com.example.ql.express.model.enums.AppendRuleEnum;
import com.example.ql.express.model.vo.ScriptConfigVO;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xuweizhi
 * @since 2021/10/28 16:05
 */
public class MessageConvertUtils {

    private MessageConvertUtils() {

    }

    public static String messageConvert(List<ScriptConfigVO> scriptConfigs) {
        if (CollectionUtils.isEmpty(scriptConfigs)) {
            return null;
        }
        Map<String, List<ScriptConfigVO>> groupConfig = scriptConfigs.stream().collect(Collectors.groupingBy(ScriptConfigVO::getParentPath));
        StringBuilder result = new StringBuilder();
        result.append("Integer value = 5;\n");
        for (Map.Entry<String, List<ScriptConfigVO>> entry : groupConfig.entrySet()) {
            List<ScriptConfigVO> value = entry.getValue();

            int size = value.size();
            String script;
            if (size == 1) {
                for (ScriptConfigVO scriptConfig : value) {
                    scriptConfig.setAppendRule(AppendRuleEnum.ALL);
                    scriptConfig.setReservedTable(SystemCharConstant.TABLE);
                    script = scriptConfig.getOperate().getOperateCompare().generateCompareRule(scriptConfig);
                    result.append(script);
                }
                continue;
            }

            for (int i = 0; i < size; i++) {
                ScriptConfigVO scriptConfig = value.get(i);
                if (i == 0) {
                    scriptConfig.setAppendRule(AppendRuleEnum.FIRST);
                } else if (i == size - 1) {
                    scriptConfig.setAppendRule(AppendRuleEnum.END);
                }
                scriptConfig.setReservedTable(SystemCharConstant.TABLE);
                script = scriptConfig.getOperate().getOperateCompare().generateCompareRule(scriptConfig);
                result.append(script);
            }
        }
        return result.toString();
    }

}
